package org.hoyi.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.hoyi.DB.ctrl.Console;
import org.hoyi.DB.ctrl.HOYI;
import org.hoyi.microservice.HoyiCloudApplication;

public class HTMLUtils {

	private static HTMLUtils _instance;

	public static HTMLUtils instance() {
		if (_instance == null) {
			_instance = new HTMLUtils();
		}
		return _instance;
	}

	/**
	 * 是否打开HTML的Cache.
	 */
	public static boolean OpenHTMLCache = true;

	/**
	 * WRITEHTML的缓存.
	 */
	private static Map<String, String> writehtmlcache = new HashMap<>();

	public String WRITEHTMLResourceAsStream(HttpServletRequest request, String url) {

		String contents = "->UNKNOWN HTML TEMPS<-";
		if (url.startsWith("\"") && url.endsWith("\"")) {
			url = url.substring(1, url.length() - 1);
		}

		if (url.trim().length() > 0 && url.contains(".")) {
			Console.Info("_requrl:" + url);
			if(OpenHTMLCache) {
				if(writehtmlcache.containsKey(url)) {
					contents = writehtmlcache.get(url);
					return contents;
				}
			}
			

			String loadurl = "WebRoot" + url;

			contents = "";
			try {
				byte[] bytes;
				// 如果是Debug模式，则直接从本地读，避免了从GetResourceAsStream导致的2,3秒的缓存问题.
				if (HoyiCloudApplication.DebugMode) {
					loadurl = HoyiCloudApplication.WebRootPath + loadurl;
					bytes = StreamUtils.Create().ReadLocalFileResource(loadurl);
				}else {
					bytes = StreamUtils.Create().ReaderResource(loadurl);	
				}
				contents = new String(bytes, "UTF-8");
			} catch (Exception e) {
				contents = "->HTML CONTENT READ ERROR<-";
			}
			
			writehtmlcache.put(url, contents);
		}
		return contents;
	}
}
